import 'package:flutter/material.dart';
import '../home/home_page.dart';
import '../../services/api_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';

class RegisterStep2Page extends StatefulWidget {
  final String phone;
  final String verificationCode; // 添加验证码参数

  const RegisterStep2Page({super.key, required this.phone, required this.verificationCode});

  @override
  State<RegisterStep2Page> createState() => _RegisterStep2PageState();
}

class _RegisterStep2PageState extends State<RegisterStep2Page> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _bioController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController();

  // 密码强度状态
  String _passwordStrengthDescription = "";
  Color _passwordStrengthColor = Colors.transparent;

  // 关注的技能 - 最多选择6个
  final List<String> _followSkills = [];
  final TextEditingController _followSkillController = TextEditingController();

  // 技能分类数据
  final Map<String, List<String>> _skillCategories = {
    '技术开发': [
      'Web开发',
      '移动开发',
      '后端开发',
      '前端开发',
      '全栈开发',
      '人工智能',
      '机器学习',
      '深度学习',
      '数据科学',
      '大数据',
      '云计算',
      'DevOps',
      '运维',
      '测试',
      '架构师',
    ],
    '设计创意': [
      'UI设计',
      'UX设计',
      '平面设计',
      '视觉设计',
      '交互设计',
      '产品设计',
      '工业设计',
      '建筑设计',
      '室内设计',
      '游戏设计',
    ],
    '商业管理': [
      '产品经理',
      '项目经理',
      '运营管理',
      '市场营销',
      '商务拓展',
      '数据分析',
      '商业分析',
      '战略规划',
      '投资分析',
      '财务管理',
    ],
    '创意策划': [
      '内容策划',
      '活动策划',
      '品牌策划',
      '营销策划',
      '创意总监',
      '文案策划',
      '新媒体运营',
      '短视频制作',
      '直播运营',
      '社群运营',
    ],
    '嵌入式硬件': [
      '嵌入式开发',
      '物联网',
      '硬件开发',
      '芯片设计',
      '自动化',
      '机器人开发',
      '智能硬件',
      '电子工程',
      '通信工程',
      '控制工程',
    ],
    '其他专业': [
      '区块链',
      '网络安全',
      '游戏开发',
      '音视频处理',
      '3D建模',
      'AR/VR开发',
      '数字孪生',
      '智慧城市',
      '医疗健康',
      '教育培训',
    ],
  };

  // 获取所有技能列表（用于兼容现有代码）
  List<String> get _presetSkills {
    List<String> allSkills = [];
    for (var skills in _skillCategories.values) {
      allSkills.addAll(skills);
    }
    return allSkills;
  }

  @override
  void initState() {
    super.initState();
    
    // 添加密码输入监听器
    _passwordController.addListener(() {
      _updatePasswordStrength(_passwordController.text);
    });
  }
  
  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    _bioController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _followSkillController.dispose();
    super.dispose();
  }
  
  // 更新密码强度显示
  void _updatePasswordStrength(String password) {
    if (password.isEmpty) {
      setState(() {
        _passwordStrengthDescription = "";
        _passwordStrengthColor = Colors.transparent;
      });
      return;
    }
    
    final result = _checkPasswordStrength(password);
    Color color;
    
    // 根据强度设置颜色
    switch (result["strength"]) {
      case 1:
      case 2:
        color = Colors.red;
        break;
      case 3:
        color = Colors.orange;
        break;
      case 4:
        color = Colors.yellow;
        break;
      case 5:
        color = Colors.green;
        break;
      default:
        color = Colors.transparent;
    }
    
    setState(() {
      _passwordStrengthDescription = result["description"];
      _passwordStrengthColor = color;
    });
  }

  // 添加关注技能 - 限制最多6个
  void _addFollowSkill() {
    final skill = _followSkillController.text.trim();
    if (skill.isNotEmpty && !_followSkills.contains(skill) && _followSkills.length < 6) {
      setState(() {
        _followSkills.add(skill);
        _followSkillController.clear();
      });
    } else if (_followSkills.length >= 6) {
      _showErrorSnackBar('最多只能选择6个关注技能');
    }
  }

  // 删除关注技能
  void _removeFollowSkill(String skill) {
    setState(() {
      _followSkills.remove(skill);
    });
  }

  // 从预设技能中选择 - 限制最多6个
  void _selectPresetSkill(String skill) {
    if (!_followSkills.contains(skill) && _followSkills.length < 6) {
      setState(() {
        _followSkills.add(skill);
      });
    } else if (_followSkills.length >= 6) {
      _showErrorSnackBar('最多只能选择6个关注技能');
    }
  }

  // 完成注册
  void _completeRegistration() async {
    final name = _nameController.text.trim();
    final email = _emailController.text.trim();
    final bio = _bioController.text.trim();
    final password = _passwordController.text.trim();
    final confirmPassword = _confirmPasswordController.text.trim();

    if (name.isEmpty) {
      _showErrorSnackBar('请输入账号');
      return;
    }

    if (email.isEmpty) {
      _showErrorSnackBar('请输入邮箱');
      return;
    }

    if (!_isValidEmail(email)) {
      _showErrorSnackBar('邮箱格式不正确');
      return;
    }

    if (_followSkills.isEmpty) {
      _showErrorSnackBar('请至少选择一个关注技能');
      return;
    }

    if (password.isEmpty || confirmPassword.isEmpty) {
      _showErrorSnackBar('请输入密码并确认密码');
      return;
    }
    if (password != confirmPassword) {
      _showErrorSnackBar('两次输入的密码不一致');
      return;
    }
    
    // 本地验证密码强度和格式
    if (!_isPasswordValid(password)) {
      if (RegExp(r'^\d+$').hasMatch(password)) {
        _showErrorSnackBar('密码不能为纯数字');
      } else {
        _showErrorSnackBar('密码强度不足，请使用包含大小写字母和数字的组合，至少8位');
      }
      return;
    }

    // 显示加载状态
    _showLoadingDialog();

    try {
      // 前端串行：先完成 step-one 获取临时ID，再调用 step-two 完成注册
      // 传递确认密码参数给registerStepOne方法
      // 优先使用前一步返回的临时ID（若已持久化）
      String? tempId;
      final prefs = await SharedPreferences.getInstance();
      tempId = prefs.getString('pending_temp_registration_id');
      if (tempId == null || tempId.isEmpty) {
        tempId = await ApiService().registerStepOne(widget.phone, password, confirmPassword, widget.verificationCode);
      }
      // 设置默认昵称（使用用户名作为默认昵称）
      final nickname = name;
      // 设置默认性别
      final gender = 'other';
      
      final result = await ApiService().registerStepTwo(
          tempRegistrationId: tempId,
          code: widget.verificationCode,
          username: name,
          nickname: nickname,
          email: email,
          bio: bio,
          gender: gender,
          skills: _followSkills, // 使用关注技能作为技能提交
        );

      // 注册成功后，保存token
      if (result.containsKey('token')) {
        ApiService().setAuthToken(result['token']);
      }

      // 清理未完成注册标记（复用上面的 prefs 实例）
      await prefs.remove('pending_registration');
      await prefs.remove('pending_phone');
      await prefs.remove('pending_code');
      await prefs.remove('pending_temp_registration_id');

      Navigator.of(context).pop(); // 关闭加载对话框
      _showSuccessSnackBar('注册成功！');

      // 延迟跳转到首页
      Future.delayed(const Duration(seconds: 1), () {
        Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (context) => const HomePage()),
          (route) => false,
        );
      });
    } catch (e) {
      Navigator.of(context).pop(); // 关闭加载对话框
      _showErrorSnackBar(e.toString());
    }
  }

  // 显示加载对话框
  void _showLoadingDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );
  }

  // 验证邮箱格式
  bool _isValidEmail(String email) {
    return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email);
  }

  // 检查密码强度
  // 返回密码强度等级(1-5)和强度描述
  Map<String, dynamic> _checkPasswordStrength(String password) {
    int strength = 0;
    String description = "弱";
    
    // 检查长度（至少8位）
    if (password.length >= 8) {
      strength++;
    }
    
    // 检查是否包含数字
    if (RegExp(r'\d').hasMatch(password)) {
      strength++;
    }
    
    // 检查是否包含小写字母
    if (RegExp(r'[a-z]').hasMatch(password)) {
      strength++;
    }
    
    // 检查是否包含大写字母
    if (RegExp(r'[A-Z]').hasMatch(password)) {
      strength++;
    }
    
    // 检查是否包含特殊字符
    if (RegExp(r'[!@#$%^&*(),.?":{}|<>]').hasMatch(password)) {
      strength++;
    }
    
    // 纯数字密码额外扣分
    if (RegExp(r'^\d+$').hasMatch(password)) {
      strength = strength > 1 ? strength - 2 : 1; // 最低保留1分
    }
    
    // 设置强度描述
    switch (strength) {
      case 1:
      case 2:
        description = "弱";
        break;
      case 3:
        description = "中等";
        break;
      case 4:
        description = "强";
        break;
      case 5:
        description = "很强";
        break;
    }
    
    return {"strength": strength, "description": description};
  }

  // 检查密码是否符合要求（至少3分，不能是纯数字）
  bool _isPasswordValid(String password) {
    if (password.isEmpty) return false;
    if (RegExp(r'^\d+$').hasMatch(password)) return false; // 不能是纯数字
    
    final result = _checkPasswordStrength(password);
    return result["strength"] >= 3;
  }

  // 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  // 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('完善信息'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 32.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 20),

              // 步骤指示器
              _buildStepIndicator(),

              const SizedBox(height: 30),

              // 基本信息
              _buildBasicInfo(),

              const SizedBox(height: 30),

              // 关注的技能
              _buildFollowSkills(),

              const SizedBox(height: 30),

              // 完成注册按钮
              _buildCompleteButton(),

              const SizedBox(height: 30),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStepIndicator() {
    return Row(
      children: [
        Expanded(
          child: Container(
            height: 4,
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
        ),
        const SizedBox(width: 8),
        Container(
          width: 20,
          height: 20,
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor,
            shape: BoxShape.circle,
          ),
          child: const Icon(
            Icons.check,
            color: Colors.white,
            size: 12,
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Container(
            height: 4,
            decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildBasicInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '基本信息',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 16),

        // 账号
              Container(
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: TextField(
                  controller: _nameController,
                  decoration: const InputDecoration(
                    hintText: '请设置账号',
                    prefixIcon: Icon(Icons.person),
                    border: InputBorder.none,
                    contentPadding: 
                        EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                  ),
                ),
              ),

        const SizedBox(height: 16),

        // 邮箱
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(12),
          ),
          child: TextField(
            controller: _emailController,
            keyboardType: TextInputType.emailAddress,
            decoration: const InputDecoration(
              hintText: '请输入邮箱',
              prefixIcon: Icon(Icons.email),
              border: InputBorder.none,
              contentPadding:
                  EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            ),
          ),
        ),

        const SizedBox(height: 16),

        // 密码
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(12),
              ),
              child: TextField(
                controller: _passwordController,
                obscureText: true,
                decoration: const InputDecoration(
                  hintText: '设置登录密码',
                  prefixIcon: Icon(Icons.lock),
                  border: InputBorder.none,
                  contentPadding:
                      EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                ),
              ),
            ),
            // 密码强度指示器
            if (_passwordStrengthDescription.isNotEmpty)
              Padding(
                padding: const EdgeInsets.only(top: 8.0, left: 8.0),
                child: Row(
                  children: [
                    Container(
                      width: 10,
                      height: 10,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: _passwordStrengthColor,
                      ),
                    ),
                    const SizedBox(width: 6),
                    Text(
                      '密码强度: $_passwordStrengthDescription',
                      style: TextStyle(
                        fontSize: 12,
                        color: _passwordStrengthColor,
                      ),
                    ),
                  ],
                ),
              ),
            // 密码要求提示
            const Padding(
              padding: EdgeInsets.only(top: 4.0, left: 8.0),
              child: Text(
                '密码要求: 至少8位，包含数字、大小写字母，不能是纯数字',
                style: TextStyle(
                  fontSize: 11,
                  color: Colors.grey,
                ),
              ),
            ),
          ],
        ),

        const SizedBox(height: 16),

        // 确认密码
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(12),
          ),
          child: TextField(
            controller: _confirmPasswordController,
            obscureText: true,
            decoration: const InputDecoration(
              hintText: '确认登录密码',
              prefixIcon: Icon(Icons.lock_outline),
              border: InputBorder.none,
              contentPadding:
                  EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            ),
          ),
        ),

        const SizedBox(height: 16),

        // 个性签名
              Container(
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: TextField(
                  controller: _bioController,
                  maxLines: 3,
                  decoration: const InputDecoration(
                    hintText: '请输入个性签名',
                    prefixIcon: Icon(Icons.edit),
                    border: InputBorder.none,
                    contentPadding: 
                        EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                  ),
                ),
              ),
      ],
    );
  }

  // Widget _buildMySkills() {
  //   return Column(
  //     crossAxisAlignment: CrossAxisAlignment.start,
  //     children: [
  //       const Text(
  //         '我的技能',
  //         style: TextStyle(
  //           fontSize: 20,
  //           fontWeight: FontWeight.bold,
  //           color: Colors.black87,
  //         ),
  //       ),
  //       const SizedBox(height: 8),
  //       const Text(
  //         '添加您擅长的技能，让更多人了解您',
  //         style: TextStyle(
  //           fontSize: 14,
  //           color: Colors.grey,
  //         ),
  //       ),
  //       const SizedBox(height: 16),

  //       // 技能输入
  //       Row(
  //         children: [
  //           Expanded(
  //             child: Container(
  //               decoration: BoxDecoration(
  //                 color: Colors.grey[100],
  //                 borderRadius: BorderRadius.circular(12),
  //               ),
  //               child: TextField(
  //                 controller: _skillController,
  //                 decoration: const InputDecoration(
  //                   hintText: '输入技能名称',
  //                   border: InputBorder.none,
  //                   contentPadding:
  //                       EdgeInsets.symmetric(horizontal: 16, vertical: 16),
  //                 ),
  //               ),
  //             ),
  //           ),
  //           const SizedBox(width: 12),
  //           ElevatedButton(
  //             onPressed: _addMySkill,
  //             style: ElevatedButton.styleFrom(
  //               backgroundColor: Theme.of(context).primaryColor,
  //               foregroundColor: Colors.white,
  //               shape: RoundedRectangleBorder(
  //                 borderRadius: BorderRadius.circular(12),
  //               ),
  //             ),
  //             child: const Text('添加'),
  //           ),
  //         ],
  //       ),

  //       const SizedBox(height: 16),

  //       // 已添加的技能
  //       if (_mySkills.isNotEmpty) ...[
  //         Wrap(
  //           spacing: 8,
  //           runSpacing: 8,
  //           children: _mySkills
  //               .map((skill) => Chip(
  //                     label: Text(skill),
  //                     deleteIcon: const Icon(Icons.close, size: 18),
  //                     onDeleted: () => _removeMySkill(skill),
  //                   ))
  //               .toList(),
  //         ),
  //         const SizedBox(height: 16),
  //       ],

  //       // 预设技能选择 - 按分类显示
  //       const Text(
  //         '常用技能',
  //         style: TextStyle(
  //           fontSize: 16,
  //           fontWeight: FontWeight.w600,
  //           color: Colors.black87,
  //         ),
  //       ),
  //       const SizedBox(height: 8),
  //       _buildSkillCategories(),
  //     ],
  //   );
  // }

  Widget _buildFollowSkills() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '关注技能',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '请在技术分类中选择关注技能，最多可选择6个',
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
        const SizedBox(height: 16),

        // 已添加的关注技能
        if (_followSkills.isNotEmpty) ...[
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: _followSkills
                .map((skill) => Chip(
                      label: Text(skill),
                      deleteIcon: const Icon(Icons.close, size: 18),
                      onDeleted: () => _removeFollowSkill(skill),
                    ))
                .toList(),
          ),
          const SizedBox(height: 16),
        ],

        // 技能选择器 - 按分类显示技术技能
        const Text(
          '技术分类',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 8),
        _buildSkillCategories(),
      ],
    );
  }

  Widget _buildCompleteButton() {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: ElevatedButton(
        onPressed: _completeRegistration,
        style: ElevatedButton.styleFrom(
          backgroundColor: Theme.of(context).primaryColor,
          foregroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: const Text(
          '完成注册',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  // 构建技能分类选择器
  Widget _buildSkillCategories() {
    return Column(
      children: _skillCategories.entries.map((entry) {
        final categoryName = entry.key;
        final skills = entry.value;

        return ExpansionTile(
          title: Text(
            categoryName,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Wrap(
                spacing: 8,
                runSpacing: 8,
                children: skills
                    .map((skill) => FilterChip(
                          label: Text(skill),
                          selected: _followSkills.contains(skill),
                          onSelected: (selected) =>
                              _selectPresetSkill(skill),
                        ))
                    .toList(),
              ),
            ),
          ],
        );
      }).toList(),
    );
  }
}
